package cn.bs.controller;


import cn.bs.domain.dao.Canteen;
import cn.bs.domain.dao.Orders;
import cn.bs.domain.dao.Seat;
import cn.bs.domain.dao.User;
import cn.bs.domain.pojo.Result;
import cn.bs.domain.pojo.OrderPOJO;
import cn.bs.domain.vo.OrderVO;
import cn.bs.mapper.CanteenMapper;
import cn.bs.mapper.OrderMapper;
import cn.bs.mapper.SeatMapper;
import cn.bs.mapper.UserMapper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CanteenMapper canteenMapper;

    @Autowired
    private SeatMapper seatMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/getOrderList")
    public Result getMyOrderList(HttpServletRequest request,
                                 @RequestParam(defaultValue = "1") int page,
                                 @RequestParam(defaultValue = "10") int size) {

        System.out.println("获取订单列表");
        System.out.println("page:" + page + " size:" + size);

        String token = request.getHeader("Authorization");
        Integer userId = Integer.valueOf(stringRedisTemplate.opsForValue().get(token));
        User user = userMapper.getById(userId);

        if (user == null) {
            return Result.fail("用户不存在");
        }
        System.out.println("用户权限 :" + user.getType());

        OrderVO orderVO = new OrderVO();
        int offset = (page - 1) * size;
        List<Orders> orders = new ArrayList<>();
        if (user.getType() == 0) {
            orders = orderMapper.getAllWithPagination(offset, size);
        } else {
            orders = orderMapper.getByUserIdWithPagination(userId, offset, size);
        }

        List<OrderPOJO> orderPOJOList = orders.stream().map(order -> {
            OrderPOJO orderPOJO = new OrderPOJO();
            orderPOJO.setId(order.getId());
            orderPOJO.setUserName(userMapper.getById(order.getUserId()).getName());
            orderPOJO.setCanteenName(canteenMapper.getById(order.getCanteenId()).getName());
            orderPOJO.setSeatId(order.getSeatId());
            orderPOJO.setOrderAmount(order.getOrderAmount());
            orderPOJO.setOrderDate(order.getOrderDate());
            orderPOJO.setPayAmount(order.getPayAmount());
            orderPOJO.setPayDate(order.getPayDate());
            Integer status = order.getStatus();
            orderPOJO.setStatus(status == 0 ? "未支付" :
                    (status == 1 ? "已支付" :
                            (status == 2 ? "已取消" : "未知状态")));
            return orderPOJO;
        }).toList();

        orderVO.setOrders(orderPOJOList);
        if(user.getType() == 0){
            orderVO.setTotal(orderMapper.getAll().size());
        }else {
            orderVO.setTotal(orderMapper.getByUserId(userId).size());
        }
        return Result.ok(orderVO);
    }


    @GetMapping("/getOrderById")
    public Result getOrderById(@RequestParam Integer orderId) {

        System.out.println("获取订单");
        System.out.println(orderId);

        if (orderMapper.getById(orderId) == null){
            return Result.fail("订单不存在");
        }

        Orders orders = orderMapper.getById(orderId);

        User user = userMapper.getById(orders.getUserId());

        Canteen canteen = canteenMapper.getById(orders.getCanteenId());

        Integer status = orders.getStatus();

        String statusStr = "";

        if (status == 0){
            statusStr = "未支付";
        }else if (status == 1){
            statusStr = "已支付";
        }else {
            statusStr = "已取消";
        }

        OrderPOJO orderPOJO = new OrderPOJO(orders.getId(), user.getName(),
                canteen.getName(), orders.getSeatId(),
                orders.getOrderAmount(), orders.getOrderDate(), orders.getPayAmount(),
                orders.getPayDate(), statusStr);

        return Result.ok(orderPOJO);
    }

    @DeleteMapping("/deleteOrdersById")
    public Result deleteOrdersById(@RequestParam String ids, HttpServletRequest request) {

        if (ids == null || ids.isEmpty()){
            return Result.fail("String为null请选择要删除的订单");
        }
        System.out.println("删除订单");
        System.out.println(ids);
        // 使用 filter 过滤掉空字符串
        List<Integer> orderIds = Arrays.stream(ids.split(","))
                .map(String::trim) // 去除前后空格
                .filter(s -> !s.isEmpty()) // 过滤掉空字符串
                .map(s -> {
                    try {
                        return Integer.parseInt(s);
                    } catch (NumberFormatException e) {
                        return null; // 返回 null 表示解析失败
                    }
                })
                .filter(Objects::nonNull) // 过滤掉解析失败的值
                .toList();

        if (orderIds.isEmpty()){
            return Result.fail("idList为null请选择要删除的订单");
        }

        int count = 0;

        StringBuilder data = new StringBuilder();

        Integer userId = Integer.valueOf(stringRedisTemplate.opsForValue().get(request.getHeader("Authorization")));

        for (Integer id : orderIds) {

            Orders order = orderMapper.getById(id);
            System.out.println("order.getUserId()" + order.getUserId());
            System.out.println("userId" + userId);
            if (order == null){
                data.append("id为").append(id).append("的订单不存在\n");
            }else if (!Objects.equals(order.getUserId(), userId) && userMapper.getById(userId).getType() != 0){
                data.append("id为").append(order.getId()).append("的订单不是您的订单或者您不是管理员，您无权删除\n");
            }else {
                orderMapper.deleteById(id);
                Seat seat = seatMapper.getById(order.getSeatId());
                seat.setStatus(0);
                seatMapper.updateById(seat);
                System.out.println("删除订单" + id);
                count++;
            }
        }

        return Result.ok("已删除" + count + "条订单\n" + data);
    }

}
